﻿/*
Copyright (c) 2005-2008, CellAO Team

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the CellAO Team nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using AO.Core;
using Cell.Core;
using ZoneEngine.Database;
using ZoneEngine.Misc;

namespace ZoneEngine.Packets
{
    /// <summary>
    /// 
    /// </summary>
    public static class SimpleCharFullUpdate
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public static void SendToPf(Client client)
        {
            Misc.Announce.Playfield(client, GetPacket(client));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public static void SendToPfOthers(Client client)
        {
            Misc.Announce.PlayfieldOthers(client, GetPacket(client));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="receiver"></param>
        public static void SendToOne(Client client, Client receiver)
        {
            byte[] data;
            data = GetPacket(client, receiver.Character.characterId);
            receiver.CmpStream.Write(data, 0, data.Length);
            receiver.CmpStream.Flush();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public static byte[] GetPacket(Client client)
        {
            return GetPacket(client, client.Character.characterId);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="receiver"></param>
        /// <returns></returns>
        public static byte[] GetPacket(Client client, int receiver)
        {
            /*
             * To set a packetFlag use:     packetFlags &= ~<flaghere>;
             * To unset a packetFlag use:   packetFlags |= <flaghere>;
             * 
             * Wherever you set a flag conditionally, be sure to unset the same flag if the reverse
             * condition is true 'just in case'
             */
            int packetFlags = 0; // Try setting to 0x042062C8 if you have problems (old value)

            PacketWriter _writer = new PacketWriter();

            // Packet Header
            _writer.PushByte(0xDF); _writer.PushByte(0xDF);
            _writer.PushShort(10);
            _writer.PushShort(1);
            _writer.PushShort(0);   // length. writer will take care of this
            _writer.PushInt(3086);  // sender. our server ID
            _writer.PushInt(receiver);  // receiver
            _writer.PushInt(0x271B3A6B);    // packet ID
            _writer.PushIdentity(50000, client.Character.characterId); // affected identity
            _writer.PushByte(0);    // ?
            // End Packet Header

            _writer.PushByte(54); // SCFU packet version (54/0x36)
            _writer.PushInt(0);   // packet flags (this is set later based on packetFlags variable above)

            packetFlags |= 0x40; // Has Playfield ID
            _writer.PushInt(client.Character.pf);   // playfield

            //if (packetFlags & 0x20)
            //{
            //    // Pop2Long
            //    /*
            //     * Is this a Type:Instance pair?
            //     * Suspect so as it uses Pop2Long
            //     * which is used for Type:Instance
            //     * pairs. Perhaps pet master?
            //     * (Just a wild guess though that its pet master)
            //     */
            //    long unknown;
            //    long unknown;
            //}

            // Coordinates
            _writer.PushCoord(client.Character.coord);

            // Heading Data
            packetFlags |= 0x200; // Has Heading Data Flag
            _writer.PushQuat(client.Character.heading);

            int m_appearance = client.Character.stats.GetStat("Side") +
            (client.Character.stats.GetStat("Fatness") * 8) +
            (client.Character.stats.GetStat("Breed") * 32) +
            (client.Character.stats.GetStat("Sex") * 256) +
            (client.Character.stats.GetStat("Race") * 1024);
            _writer.PushInt(m_appearance);  // appearance

            // Name
            _writer.PushByte((byte)(client.Character.characterName.Length + 1));
            _writer.PushBytes(Encoding.ASCII.GetBytes(client.Character.characterName));
            _writer.PushByte(0);    // 0 terminator for name

            _writer.PushInt(client.Character.stats.GetStat("Flags"));
            _writer.PushShort((short)client.Character.stats.GetStat("AccountFlags"));
            _writer.PushShort((short)client.Character.stats.GetStat("Expansion"));

            packetFlags &= ~0x01; // We are a player
            if ((packetFlags & 0x01) != 0)
            {
                // Are we a NPC (i think anyway)? So far this is _NOT_ used at all

                //if (packetFlags & 0x20000)
                //{
                //    char NPCFamily;
                //}
                //else
                //{
                //    short NPCFamily;
                //}

                //if (packetFlags & 0x80000)
                //{
                //    char LOSHeight?;
                //}
                //else
                //{
                //    short LOSHeight?;
                //}

                //if (packetFlags & 0x2000000)
                //{
                //    char PetType;
                //}
                //else
                //{
                //    short PetType;
                //}

                //short TowerType;

                //if (TowerType > 0)
                //{
                //    char unknown;
                //}
            }
            else
            {
                // Are we a player?
                _writer.PushInt(client.Character.stats.GetStat("CurrentNano"));
                _writer.PushInt(0); // team?
                _writer.PushShort(5);   // swim?

                // The checks here are to prevent the client doing weird things if the character has really large or small base attributes
                if (client.Character.stats.GetStat("Strength") > 32767)
                {
                    _writer.PushShort((short)32767);
                }
                else if (client.Character.stats.GetStat("Strength") < -32768)
                {
                    _writer.PushShort((short)-32768);
                }
                else
                {
                    _writer.PushShort((short)client.Character.stats.GetStat("Strength"));
                }
                if (client.Character.stats.GetStat("Agility") > 32767)
                {
                    _writer.PushShort((short)32767);
                }
                else if (client.Character.stats.GetStat("Agility") < -32768)
                {
                    _writer.PushShort((short)-32768);
                }
                else
                {
                    _writer.PushShort((short)client.Character.stats.GetStat("Agility"));
                }
                if (client.Character.stats.GetStat("Stamina") > 32767)
                {
                    _writer.PushShort((short)32767);
                }
                else if (client.Character.stats.GetStat("Stamina") < -32768)
                {
                    _writer.PushShort((short)-32768);
                }
                else
                {
                    _writer.PushShort((short)client.Character.stats.GetStat("Stamina"));
                }

                if ((client.Character.stats.GetStat("Flags") & 0x400000) != 0)  // has visible names?
                {
                    _writer.PushShort((short)client.Character.characterFirstName.Length);
                    _writer.PushBytes(Encoding.ASCII.GetBytes(client.Character.characterFirstName));
                    _writer.PushShort((short)client.Character.characterLastName.Length);
                    _writer.PushBytes(Encoding.ASCII.GetBytes(client.Character.characterLastName));
                }

                if (client.Character.orgName.Length != 0)
                {
                    packetFlags |= 0x4000000; // Has org name data

                    _writer.PushShort((short)client.Character.orgName.Length);
                    _writer.PushBytes(Encoding.ASCII.GetBytes(client.Character.orgName));
                }
                else
                {
                    packetFlags &= ~0x4000000; // Does not have org name data
                }
            }

            if ((client.Character.stats.GetStat("Level") > 127) || (client.Character.stats.GetStat("Level") < -128))
            {
                packetFlags |= 0x1000; // Has Extended Level
                _writer.PushShort((short)client.Character.stats.GetStat("Level"));
            }
            else
            {
                packetFlags &= ~0x1000; // Has Small Level
                _writer.PushByte((byte)client.Character.stats.GetStat("Level"));
            }

            if ((client.Character.stats.GetStat("Health") > 32767) || (client.Character.stats.GetStat("Health") < -32768))
            {
                packetFlags &= ~0x800; // Has Extended Health
                _writer.PushInt(client.Character.stats.GetStat("Health"));
            }
            else
            {
                packetFlags |= 0x800; // Has Small Health
                _writer.PushShort((short)client.Character.stats.GetStat("Health"));
            }

            packetFlags |= 0x4000; // If this is not set, then we have a short or long based on flag 0x800 (Health size)
            if ((packetFlags & 0x4000) != 0)
            {
                _writer.PushByte(0);    // ?
            }
            else
            {
                //if (packetFlags & 0x800)
                //{
                //    short unknown;
                //}
                //else
                //{
                //    long unknown;
                //}
            }

            _writer.PushInt(client.Character.stats.GetStat("MonsterData"));
            _writer.PushShort((short)client.Character.stats.GetStat("MonsterScale"));
            _writer.PushShort((short)client.Character.stats.GetStat("VisualFlags"));
            _writer.PushByte(0);    // visible title?

            _writer.PushInt(42);    // 'skipdata' length
            // Start 'skipdata'
            _writer.PushBytes(new byte[]
            {
                0x80, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00,
                0x80, 0x00, 0x00, 0x00
            });
            _writer.PushByte((byte)client.Character.stats.GetStat("CurrentMovementMode"));
            _writer.PushByte(1);    // don't change
            _writer.PushShort(1);   // ?
            _writer.PushShort(1);   // ?
            _writer.PushShort(1);   // ?
            _writer.PushShort(1);   // ?
            _writer.PushShort(0);   // ?
            _writer.PushShort(3);   // ?
            _writer.PushInt(0); //?
            _writer.PushInt(0); //?
            _writer.PushInt(0); //?
            _writer.PushInt(0); //?
            // End 'skipdata'

            packetFlags |= 0x80; // Has HeadMesh Flag
            _writer.PushInt(client.Character.stats.GetStat("HeadMesh"));

            if ((client.Character.stats.GetStat("RunSpeed") > 127) || (client.Character.stats.GetStat("RunSpeed") < -128))
            {
                packetFlags |= 0x2000;
                _writer.PushShort((short)client.Character.stats.GetStat("RunSpeed"));
            }
            else
            {
                packetFlags &= ~0x2000;
                _writer.PushByte((byte)client.Character.stats.GetStat("RunSpeed"));
            }

            //if (packetFlags & 0x400)
            //{
            //    // Pop2Long
            //    /*
            //     * Is this a Type:Instance pair?
            //     * Suspect so as it uses Pop2Long
            //     * which is used for Type:Instance
            //     * pairs. Perhaps pet master?
            //     * (Just a wild guess though that its pet master)
            //     */
            //    long unknown;
            //    long unknown;
            //}

            //if (packetFlags & 0x10)
            //{
            //    long counter;
            //    repeat (counter / 0x3F1 - 1) times
            //        char texturepositionname[32]; // Null padded at the end
            //        long textureid; // Or is this mesh id? (Damn you suiv :P)
            //        long unknown;
            //        long unknown;
            //    end repeat
            //}

            //if (packetFlags & 0x100000)
            //{
            //    short unknown;
            //}

            //if (packetFlags & 0x800000)
            //{
            //    char unknown;
            //}

            //if (packetFlags & 0x1000000)
            //{
            //    char unknown;
            //}

            _writer.Push3F1Count(0);    // running nanos count
            // longx5: aoid, instance, unknown(0?), timer1, timer2

            //if (flags & 0x10000)
            //{
            //    // Waypoint Info
            //    // Pop2Long (1010E2D3)
            //    long type;
            //    long instance;
            //    // Waypoint Counter - 3x float per entry
            //    long counter;
            //    repeat counter times
            //        float x;
            //        float y;
            //        float z;
            //    end repeat
            //    // End Waypoint Counter
            //}

            // Texture/Cloth Data
            Textures tx = new Textures();
            tx.GetTextures(client.Character.characterId);
            _writer.Push3F1Count(5);    // textures count
            // Texture 1
            _writer.PushInt(0);
            _writer.PushInt(tx.Textures0);
            _writer.PushInt(0);
            // Texture 2
            _writer.PushInt(1);
            _writer.PushInt(tx.Textures1);
            _writer.PushInt(0);
            // Texture 3
            _writer.PushInt(2);
            _writer.PushInt(tx.Textures2);
            _writer.PushInt(0);
            // Texture 4
            _writer.PushInt(3);
            _writer.PushInt(tx.Textures3);
            _writer.PushInt(0);
            // Texture 5
            _writer.PushInt(4);
            _writer.PushInt(tx.Textures4);
            _writer.PushInt(0);
            // End Textures

            // Meshs
            _writer.Push3F1Count(1);    // mesh count
            // Mesh 1
            _writer.PushByte(0);
            _writer.PushInt(client.Character.stats.GetStat("HeadMesh"));
            _writer.PushInt(0);
            _writer.PushByte(4);
            // End Meshs

            //if (packetFlags & 0x100)
            //{
            //    // 0x3F1 Unknown Counter - 4x long per entry
            //    long counter;
            //    repeat (counter / 0x3F1 - 1) times
            //        long unknown;
            //        long unknown;
            //        long unknown;
            //        long unknown;
            //    end repeat
            //}

            //if (packetFlags & 0x20000000)
            //{
            //    char unknown;
            //}

            //if (packetFlags & 0x40000000)
            //{
            //    // 0x3F1 Unknown Counter - 4x long per entry
            //    long counter;
            //    repeat (counter / 0x3F1 - 1) times
            //        Pop2Long (Type:Instance pair maybe?)
            //        long unknown;
            //        long unknown;
            //    end repeat
            //}

            _writer.PushInt(0); // packetFlags2

            //if (packetFlags2 & 0x01)
            //{
            //    long counter;
            //    repeat (counter) times
            //        long unknown;
            //        long unknown;
            //    end repeat

            //    long unknown;
            //    // Pop2Long (Type:Instance pair maybe?)
            //    long unknown;
            //    long unknown;
            //}

            //if (packetFlags2 & 0x02)
            //{
            //    char unknown;
            //}

            //if (packetFlags2 & 0x04)
            //{
            //    long unknown;
            //}

            byte[] reply = _writer.Finish();

            // Set Packet Flags
            byte[] m_packetFlags;
            m_packetFlags = BitConverter.GetBytes(packetFlags);
            Array.Reverse(m_packetFlags);
            reply[30] = m_packetFlags[0]; reply[31] = m_packetFlags[1];
            reply[32] = m_packetFlags[2]; reply[33] = m_packetFlags[3];

            return reply;
        }
    }
}
